<template>
	<view class="editReport ff-font-14 ff-color-000">
		<!-- <f-navbar title="填写报告书（检测）" :iconLeft="true" :isBack="true" @goBack="goBack" /> -->
		<view>
			<cover-view class="navBar ff-flex" :style="navStyle">
				<cover-view class="content ff-text-center">
					<cover-view class="iconLeft ff-align-items-one" @click="goBack">
						<cover-image class="leftIcon"
							src="https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/back.png"
							mode="" /></cover-image>
					</cover-view>
					填写报告书（检测）
				</cover-view>
			</cover-view>
			<!-- <cover-view :style="tabberStyle"></cover-view> -->
		</view>
		<view class="editReportBox" :style="tabberStyle1">
			<view class="ff-padding-top-2">
				<view class="editReport-content ff-border-radius-10 ff-bg-fff">
					<view class="ff-font-16 ff-font-weight-600 ff-margin-bottom-12">存在问题及整改措施</view>
					<textarea v-model="params.question" maxlength="-1" placeholder="请输入存在问题及整改措施"
						class="ff-color-222 ff-border-radius-10" />
				</view>
				<view class="editReport-content ff-border-radius-10 ff-bg-fff">
					<view class="ff-padding-bottom-15 ff-border-bottom">
						<view class="ff-font-16 ff-font-weight-600 ff-margin-bottom-12">检测结论</view>
						<view class="ff-align-items-one">
							<view class="ff-margin-right-30">直接判定情况</view>
							<u-radio-group size="40" width="140rpx" v-model="params.assessImmediateResult">
								<u-radio @change="radioResultChange" v-for="(item, index) of relustList" :key="index"
									:name="item.id">{{ item.name }}</u-radio>
							</u-radio-group>
						</view>
					</view>
					<view class="ff-margin-top-15 ff-border-bottom ff-padding-bottom-15">
						<view class="ff-margin-bottom-15">综合判定情况</view>
						<u-table padding="25rpx 0">
							<u-tr>
								<u-th>检测单元</u-th>
								<u-th>权重（%）</u-th>
								<u-th>实际得分</u-th>
							</u-tr>
							<u-tr v-for="(item, index) of params.units" :key="index">
								<u-td>{{ item.unitName }}</u-td>
								<u-td><input type="digit" @input="fireFractionInput(item.weight, index)"
										v-model="item.weight" placeholder="请输入" /></u-td>
								<u-td><input type="digit" @input="fireFractionInput(item.actualScore, index)"
										v-model="item.actualScore" placeholder="请输入" /></u-td>
							</u-tr>
							<u-tr>
								<u-td>合计</u-td>
								<u-td>/</u-td>
								<u-td>{{ params.assessFinalScore }}</u-td>
							</u-tr>
						</u-table>
						<view class="tips ff-margin-top-15 ff-line-height-1-4 ff-border-radius-10 ff-font-12">
							判定标准
							<br />
							低于60份，结论为“差”；
							<br />
							60分（含）以上85分以下，结论为“一般”;
							<br />
							85分（含）以上，结论为“好”；
						</view>
					</view>
					<view class="ff-padding-top-15 ff-padding-bottom-5">
						<view class="ff-align-items-one">
							<view class="ff-margin-right-10">最终检测结论：</view>
							<view>
								<text class="ff-color-red" v-if="params.assessFinalResult == 1">差</text>
								<text class="ff-color-orange" v-if="params.assessFinalResult == 2">一般</text>
								<text class="ff-color-blue" v-if="params.assessFinalResult == 3">好</text>
							</view>
						</view>
					</view>
				</view>
				<view class="editReport-content ff-border-radius-10 ff-bg-fff">
					<view class="ff-font-16 ff-font-weight-600 ff-margin-bottom-12">其他问题说明</view>
					<view v-for="(item, index) of params.otherQuestions" :key="index">
						<view v-if="item.isOtherSuggestion == 2">
							<view class="tips ff-margin-top-15 ff-line-height-1-4 ff-border-radius-10 ff-font-12">
								{{ item.questionExplain }}
							</view>
							<view class="ff-margin-top-20 ff-margin-bottom-15">存在问题</view>
							<textarea v-model="item.existProblem" maxlength="-1" placeholder="请输入存在问题"
								class="ff-color-222 ff-border-radius-10" />
							<view class="ff-margin-top-20 ff-margin-bottom-15">整改建议</view>
							<textarea v-model="item.recommendations" maxlength="-1" placeholder="请输入整改建议"
								class="ff-color-222 ff-border-radius-10" />
							<view class="ff-margin-top-15">
								<u-row gutter="20">
									<u-col span="3" v-for="(item, ind) of item.questionExplainAttachs" :key="ind">
										<view class="ff-margin-bottom-10 ff-relative"
											@click="previewQuestionImg(index, ind)">
											<image class="upateImg" :src="item" mode="" />
											<view @click.stop="deteleQuestionImg(index, ind)" class="closeIcon"><u-icon
													name="close" color="#fff" size="22"></u-icon></view>
										</view>
									</u-col>
									<u-col span="3">
										<image class="upateImg" @click="upateQuestionImg(index)"
											src="https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/upate-icon.png"
											mode="" />
									</u-col>
								</u-row>
							</view>
						</view>
						<view v-if="item.isOtherSuggestion == 1">
							<view class="tips ff-margin-top-20 ff-line-height-1-4 ff-border-radius-5 ff-font-12">
								{{ item.questionExplain }}
							</view>
							<textarea v-model="item.otherRecommendation" maxlength="-1" placeholder="请输入其他建议"
								class="ff-color-222 ff-margin-top-15 ff-border-radius-10" />
							<view class="ff-margin-top-15">
								<u-row gutter="20">
									<u-col span="3" v-for="(item, ind) of item.questionExplainAttachs" :key="ind">
										<view class="ff-margin-bottom-10 ff-relative"
											@click="previewQuestionImg(index, ind)">
											<image class="upateImg" :src="item" mode="" />
											<view @click.stop="deteleQuestionImg(index, ind)" class="closeIcon"><u-icon
													name="close" color="#fff" size="22"></u-icon></view>
										</view>
									</u-col>
									<u-col span="3">
										<image class="upateImg" @click="upateQuestionImg(index)"
											src="https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/upate-icon.png"
											mode="" />
									</u-col>
								</u-row>
							</view>
						</view>
					</view>
				</view>
				<view class="editReport-content ff-border-radius-10 ff-bg-fff">
					<view class="ff-font-16 ff-font-weight-600 ff-margin-bottom-15">附件</view>
					<u-row gutter="20">
						<u-col span="3" v-for="(item, index) of params.attachs" :key="index">
							<view class="ff-margin-bottom-10 ff-relative" @click="viewImageAttachs(item)">
								<image class="upateImg" :src="item" mode="" />
								<view @click.stop="delImgAttachs(index)" class="closeIcon"><u-icon name="close"
										color="#fff" size="22"></u-icon></view>
							</view>
						</u-col>
						<u-col span="3">
							<image class="upateImg" @click="chooseImageAttachs"
								src="https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/upate-icon.png"
								mode="" />
						</u-col>
					</u-row>
				</view>
			</view>
			<view class="editReport-but"><u-button type="primary" shape="circle" @click="submitClick">确定提交</u-button>
			</view>
		</view>

		<!-- -----------------------------弹框区------------------------------ -->
		<u-toast ref="uToast" />
		<f-loading ref="loading" />
		<!-- helangCompress-压缩图片 -->
		<f-compressImg ref="helangCompress" />
	</view>
</template>

<script>
	export default {
		name: 'editReport',
		data() {
			return {
				editState: true, // 编辑or填写
				submitUrl: '', // 提交的url
				relustList: [{
					name: '差',
					id: 1
				}, {
					name: '一般',
					id: 2
				}, {
					name: '好',
					id: 3
				}],
				// 上传给后台的参数
				params: {
					assessId: '', // 检测id
					question: '', // 问题
					assessImmediateResult: '', // 直接判定情况(1.差 2.一般 3.好)
					units: [], // 检测单元
					assessFinalScore: '', // 最终得分
					assessFinalResult: '', // 最终检测结论(1.差 2.一般 3.好)
					otherQuestions: [], // 其它问题说明模板
					attachs: [] // 附件
				},
				reportInfo: {}, // 报告书详情
				oldDataLength: '' // 原始字符长度
			};
		},
		onLoad(e) {
			// console.log('前页面传过来的数据------', e);
			this.params.assessId = e.id;
			if (e.type == 1) {
				// 编辑报告书
				this.editState = true;
				this.getReportInfo(e.id); // 获取报告书详情数据
			} else {
				this.getAssessUnitList(); // 获取检测单元得字段
				this.getTempQuestionExplainList(); // 获取其他问题说明模板
			}
			setTimeout(() => {
				this.oldDataLength = JSON.stringify(this.params).length;
			}, 260);
		},
		computed: {
			navStyle() { //height:${this.customBar}px;
				return `padding:${this.statusBar+30}px 20rpx 30rpx;`;
			},
			// tabberStyle() {
			// 	return `height:${this.customBar}px;`;
			// },
			tabberStyle1() {
				return `margin-top:${this.customBar+20}px;`;
			}
		},
		methods: {
			customBack(e) {
				// console.log('八嘎')
			},
			// 返回上一层
			goBack() {
				if (this.oldDataLength != JSON.stringify(this.params).length) {
					uni.showModal({
						title: '温馨提示',
						content: '当前页面所填内容将不被保存，请谨慎操作！',
						showCancel: true, // 是否显示取消按钮，默认为 true
						cancelText: '取消', // 取消按钮的文字
						confirmText: '确认返回', // 确认按钮的文字
						confirmColor: '#3178FF',
						cancelColor: '#606266',
						success: function(res) {
							if (res.confirm) {
								uni.navigateBack({
									delta: 1
								});
							}
						}
					});
				} else {
					uni.navigateBack({
						delta: 1
					});
				}
			},
			// 获取报告书详情数据
			async getReportInfo(assessId) {
				this.$refs.loading.openLoading('加载中···');
				const data = await this.$http.get({
					url: `/bsAssessProjectInfo/getReport/${assessId}`
				});
				// console.log('获取报告书详情数据-----', data);
				if (data.code == 200) {
					let dat = data.data;
					this.reportInfo = dat;
					this.params.question = dat.question;
					this.params.assessImmediateResult = dat.assessImmediateResult;
					this.params.units = dat.units;
					this.params.assessFinalScore = dat.assessFinalScore || 0;
					this.params.assessFinalResult = dat.assessFinalResult;
					this.params.otherQuestions = dat.otherQuestions;
					this.params.attachs = dat.attachs;
				}
				this.$refs.loading.closeLoading();
			},
			// 获取检测单元得字段
			async getAssessUnitList() {
				this.$refs.loading.openLoading('加载中···');
				const data = await this.$http.get({
					url: `/sys/macro/catalog/assess_unit`
				});
				if (data.code == 200) {
					// console.log('获取检测单元得字段', data);
					data.data.map(data => {
						this.params.units.push({
							unitId: data.id, // 检测单元ID(字典ID)
							weight: '', // 权重
							actualScore: '', // 实际得分
							unitName: data.macroName
						});
					});
				}
				this.$refs.loading.closeLoading();
			},
			// 获取其他问题说明模板
			async getTempQuestionExplainList() {
				this.$refs.loading.openLoading('加载中···');
				const data = await this.$http.get({
					url: '/bsAssessProjectInfo/getTempQuestionExplainList'
				});
				// console.log('获取其他问题说明模板', data);
				if (data.code == 200) {
					data.data.forEach(item => {
						this.params.otherQuestions.push({
							explainId: item.explainId, // 其他问题说明ID
							questionExplain: item.questionExplain, // 其他问题说明
							isOtherSuggestion: item.isOtherSuggestion, // 是否是其他建议(1.是 2.否)
							existProblem: '', // 存在问题
							recommendations: '', // 整改建议
							otherRecommendation: '', // 其他建议
							questionExplainAttachs: [] // 照片集合
						});
					});
				}
				this.$refs.loading.closeLoading();
			},
			// 点击判定结果选择
			radioResultChange(e) {
				if (e == 1) {
					this.params.assessImmediateResult = 1;
				} else if (e == 2) {
					this.params.assessImmediateResult = 2;
				} else if (e == 3) {
					this.params.assessImmediateResult = 3;
				}
			},
			// 消防检测单元评分
			fireFractionInput(e, index) {
				// console.log(e, index);
				if (index == 0 && e == this.params.units[0].weight) {
					this.params.assessFinalScore = (
						(Number(e) / 100) * Number(this.params.units[0].actualScore) +
						(Number(this.params.units[1].weight) / 100) * Number(this.params.units[1].actualScore) +
						(Number(this.params.units[2].weight) / 100) * Number(this.params.units[2].actualScore)
					).toFixed(2);
				} else if (index == 0 && e == this.params.units[0].actualScore) {
					this.params.assessFinalScore = ((this.params.units[0].weight / 100) * e + (Number(this.params.units[1]
							.weight) / 100) * Number(this.params.units[1].actualScore) +
						(Number(this.params.units[2].weight) / 100) * Number(this.params.units[2].actualScore)
					).toFixed(2);
				} else if (index == 1 && e == this.params.units[1].weight) {
					this.params.assessFinalScore = (
						(this.params.units[0].weight / 100) * Number(this.params.units[0].actualScore) +
						(Number(e) / 100) * Number(this.params.units[1].actualScore) +
						(Number(this.params.units[2].weight) / 100) * Number(this.params.units[2].actualScore)
					).toFixed(2);

				} else if (index == 1 && e == this.params.units[1].actualScore) {
					this.params.assessFinalScore = (
						(this.params.units[0].weight / 100) * Number(this.params.units[0].actualScore) +
						(Number(this.params.units[1].weight) / 100) * e +
						(Number(this.params.units[2].weight) / 100) * Number(this.params.units[2].actualScore)
					).toFixed(2);
				} else if (index == 2 && e == this.params.units[2].weight) {
					this.params.assessFinalScore = (
						(this.params.units[0].weight / 100) * Number(this.params.units[0].actualScore) +
						(Number(this.params.units[1].weight) / 100) * Number(this.params.units[1].actualScore) +
						(Number(e) / 100) * Number(this.params.units[2].actualScore)
					).toFixed(2);
				} else if (index == 2 && e == this.params.units[2].actualScore) {
					this.params.assessFinalScore = (
						(this.params.units[0].weight / 100) * Number(this.params.units[0].actualScore) +
						(Number(this.params.units[1].weight) / 100) * Number(this.params.units[1].actualScore) +
						(Number(this.params.units[2].weight) / 100) * e
					).toFixed(2);
				}

				// 判断最终得检测结论
				if (this.params.assessFinalScore < 60) {
					this.params.assessFinalResult = 1;
				} else if (this.params.assessFinalScore >= 60 && this.params.assessFinalScore < 85) {
					this.params.assessFinalResult = 2;
				} else if (this.params.assessFinalScore >= 85) {
					this.params.assessFinalResult = 3;
				}
				// console.log('this.params.assessFinalResult', this.params.assessFinalScore, this.params.assessFinalResult);
			},

			// 上传问题的图片------------------------------------------
			// 上传问题-----照片
			upateQuestionImg(index) {
				let that = this;
				uni.chooseMedia({
					count: 1, // 默认9
					mediaType: ['image'], // 拍照 video：视频
					camera: 'back', // 前置摄像头
					sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'], // 相机拍摄
					success: res => {
						that.$refs.loading.openLoading('上传中···');
						that.$refs.helangCompress
							.compress({
								src: res.tempFiles[0].tempFilePath
								// maxSize: 1080,
								// fileType: 'jpg',
								// quality: 0.85
								// minSize: 640 //最小压缩尺寸，图片尺寸小于该时值不压缩，非H5平台有效。若需要忽略该设置，可设置为一个极小的值，比如负数。
							})
							.then(res => {
								// 压缩成功回调
								// console.log('压缩成功回调', res);
								that.$uploadImg.uploadImgOSS(res, 8).then(res => {
									if (res) {
										// console.log('压缩成功回调', res);
										that.params.otherQuestions[index].questionExplainAttachs
											.push(res);
									} else {
										that.$refs.uToast.show({
											title: '上传照片失败，请重新上传！',
											type: 'error'
										});
									}
									that.$refs.loading.closeLoading();
								});
							});
					}
				});
			},
			// 预览问题----照片
			previewQuestionImg(index, ind) {
				uni.previewImage({
					urls: this.params.otherQuestions[index].questionExplainAttachs,
					current: this.params.otherQuestions[index].questionExplainAttachs[ind]
				});
			},
			// 删除问题-----照片
			deteleQuestionImg(index, ind) {
				this.params.otherQuestions[index].questionExplainAttachs.splice(ind, 1);
			},

			// 上传附件------------------------------------------
			// 上传附件-----照片
			chooseImageAttachs() {
				let that = this;
				uni.chooseMedia({
					count: 1, // 默认9
					mediaType: ['image'], // 拍照 video：视频
					camera: 'back', // 前置摄像头
					sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'], // 相机拍摄
					success: res => {
						that.$refs.loading.openLoading('上传中···');
						that.$refs.helangCompress
							.compress({
								src: res.tempFiles[0].tempFilePath
								// maxSize: 1080,
								// fileType: 'jpg',
								// quality: 0.85
								// minSize: 640 //最小压缩尺寸，图片尺寸小于该时值不压缩，非H5平台有效。若需要忽略该设置，可设置为一个极小的值，比如负数。
							})
							.then(res => {
								// 压缩成功回调
								// console.log('压缩成功回调', res);
								that.$uploadImg.uploadImgOSS(res, 8).then(res => {
									if (res) {
										that.params.attachs.push(res);
									} else {
										that.$refs.uToast.show({
											title: '上传照片失败，请重新上传！',
											type: 'error'
										});
									}
									that.$refs.loading.closeLoading();
								});
							});
					}
				});
			},
			// 预览附件----照片
			viewImageAttachs(item) {
				uni.previewImage({
					urls: this.params.attachs,
					current: item
				});
			},
			// 删除附件(照片)
			delImgAttachs(index) {
				this.params.attachs.splice(index, 1);
			},

			// 确定提交----操作
			submitClick() {
				let that = this;
				if (!that.params.assessImmediateResult) {
					uni.showModal({
						title: '',
						content: '请选择直接判定情况',
						confirmColor: '#3178FF',
						confirmText: '确认',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {}
						}
					})
					return;
				}
				if (!that.$check.numberCheck(this.params.units[0].weight)) {
					uni.showModal({
						title: '',
						content: '消防安全管理的权重必须是正整数',
						confirmColor: '#3178FF',
						confirmText: '确认',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {}
						}
					})
					return;
				}
				if (!that.$check.numberCheck(this.params.units[1].weight)) {
					uni.showModal({
						title: '',
						content: '建筑防火的权重必须是正整数',
						confirmColor: '#3178FF',
						confirmText: '确认',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {}
						}
					})
					return;
				}
				if (!that.$check.numberCheck(this.params.units[2].weight)) {
					uni.showModal({
						title: '',
						content: '消防设施的权重必须是正整数',
						confirmColor: '#3178FF',
						confirmText: '确认',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {}
						}
					})
					return;
				}
				if (Number(this.params.units[0].weight) + Number(this.params.units[1].weight) + Number(this.params.units[2]
						.weight) != 100) {
					uni.showModal({
						title: '',
						content: '权重比之和要等于100%',
						confirmColor: '#3178FF',
						confirmText: '确认',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {}
						}
					})
					return;
				}
				if (!that.$check.numberCheckPoint(this.params.units[0].actualScore)) {
					uni.showModal({
						title: '',
						content: '消防安全管理的实际得分必须为正数或小数点后两位',
						confirmColor: '#3178FF',
						confirmText: '确认',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {}
						}
					})
					return;
				}
				if (!that.$check.numberCheckPoint(this.params.units[1].actualScore)) {
					uni.showModal({
						title: '',
						content: '建筑防火的实际得分必须为正数或小数点后两位',
						confirmColor: '#3178FF',
						confirmText: '确认',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {}
						}
					})
					return;
				}
				if (!that.$check.numberCheckPoint(this.params.units[2].actualScore)) {
					uni.showModal({
						title: '',
						content: '消防设施的实际得分必须为正数或小数点后两位',
						confirmColor: '#3178FF',
						confirmText: '确认',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {}
						}
					})
					return;
				}
				uni.showModal({
					title: '请确认是否提交审核？',
					content: '提交后等待负责人审核',
					confirmColor: '#3178FF',
					cancelColor: '#606266',
					success: res => {
						if (res.confirm) {
							that.$refs.loading.openLoading('提交中···');
							if (that.editState) {
								// 判断首次提交或者是编辑的地址
								that.submitUrl = '/bsAssessProjectInfo/updateReport';
							} else {
								that.submitUrl = '/bsAssessProjectInfo/saveReport';
							}
							that.$http
								.post({
									url: that.submitUrl,
									data: that.params
								})
								.then(res => {
									// console.log('提交审核结果------', res);
									that.$refs.loading.closeLoading();
									if (res.code == 200) {
										that.$refs.uToast.show({
											title: res.msg,
											type: 'success'
										});
										setTimeout(() => {
											that.$pageJump.reLaunch(
												'/pages/detection/mechanism/Maintenance');
										}, 500);
									} else {
										uni.showModal({
											title: '',
											content: res.msg,
											confirmColor: '#3178FF',
											confirmText: '确认',
											showCancel: false,
											success: function(res) {
												if (res.confirm) {}
											}
										})
									}
								});
						}
					}
				});
			}
		},
		onShareAppMessage() {
			return {
				title: '分享小程序给朋友',
				path: '/pages/homePage/Home'
			};
		}
	};
</script>

<style lang="scss" scoped>
	.editReport {
		.navBar {
			position: fixed;
			left: 0;
			top: 0;
			width: 100%;
			z-index: 99999;
			background-color: #3178ff;
			color: #ffffff;

			.content {
				flex: 1;
				font-size: 32rpx;
				font-weight: 500;
				display: flex;
				align-items: center;
				justify-content: center;

				.iconLeft {
					position: absolute;
					left: 0;
					padding: 10rpx 25rpx;
					font-size: 30rpx;
					font-weight: 400;
					display: flex;
					align-items: center;
					justify-content: center;

					.leftIcon {
						width: 35rpx;
						height: 35rpx;
					}

					/deep/.arrow-left {
						font-weight: 300 !important;
						margin-right: 6rpx;
					}
				}
			}
		}

		&-content {
			padding: 28rpx 24rpx;
			margin: 20rpx;

			textarea {
				background-color: #f7f8fa;
				width: 94%;
				padding: 16rpx 21rpx;
				height: 200rpx;
			}

			.tips {
				background-color: #f4f7ff;
				padding: 18rpx 26rpx;
			}

			.upateImg {
				width: 100%;
				height: 140rpx;
			}
		}

		&-but {
			width: 90%;
			margin: 15% 5% 10%;
			padding-bottom: 100rpx;

			/deep/.u-size-default {
				height: 90rpx !important;
				line-height: 90rpx !important;
			}
		}
	}
</style>